package handler

import (
	"github.com/gin-gonic/gin"
	"time"
	"zk11_4-core/caches"
	"zk11_4-core/models"
	"zk11_4-core/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if password == "" || username == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不完整",
		})
		return
	}
	redis_key := "login_" + username
	errCount, _ := caches.Rdb.Get(caches.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		caches.Rdb.Incr(caches.Ctx, redis_key)
		if errCount == 2 {
			caches.Rdb.Set(caches.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
